package q124;

/**
 * 124. 二叉树中的最大路径和
 */
public class Solution {

    long maxSum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return (int) maxSum;
    }

    public long dfs(TreeNode root) {
        if (root == null) return Integer.MIN_VALUE;
        long lMax = dfs(root.left);
        long rMax = dfs(root.right);
        if (lMax == Integer.MIN_VALUE && rMax == Integer.MIN_VALUE) {
            maxSum = Math.max(maxSum, root.val);
            return root.val;
        } else if (lMax == Integer.MIN_VALUE) {
            maxSum = Math.max(Math.max(Math.max(root.val, rMax), root.val + rMax), maxSum);
            return Math.max(root.val + rMax, root.val);
        } else if (rMax == Integer.MIN_VALUE) {
            maxSum = Math.max(Math.max(Math.max(root.val, lMax), root.val + lMax), maxSum);
            return Math.max(root.val + lMax, root.val);
        } else {
            maxSum = Math.max(Math.max(Math.max(Math.max(Math.max(Math.max(lMax, rMax), root.val), root.val + lMax), root.val + rMax), root.val + lMax + rMax), maxSum);
            return Math.max(Math.max(root.val + lMax, root.val + rMax), root.val);
        }
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static void main(String[] args) {
        System.out.println(294967296);
    }
}

